<!-- 图片文件上传 -->
<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :limit="2"
      :http-request="uploadFiles"
      :on-remove="handleRemove"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  name: "uploadImage",
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      imageUrl: "",
    };
  },
  props: {
    fileUrl: {
      required: true,
    },
  },

  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    fileUrl(newV, oldV) {
      this.imageUrl = newV;
    },
  },
  //方法集合
  methods: {
    beforeAvatarUpload(file) {
      //   const isJPG = file.type === "image/jpeg";
      //   if (!isJPG) {
      //     this.$message.error("上传头像图片只能是 JPG 格式!");
      //   }
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isLt20M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt20M;
    },
    handleRemove() {},
    uploadFiles(file) {
      let formData = new FormData();
      formData.append("file", file.file);
      this.$http({
        url: this.$http.adornUrl("/sys/oss/upload"),
        headers: { "Content-Type": "multipart/form-data" },
        method: "post",
        data: formData,
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message.success("上传成功！");
          this.imageUrl = data.url;
          this.$emit("parent-event", this.imageUrl);
        } else {
          this.$message.error(data.msg);
        }
      });
    },
  },
};
</script>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>